package com.fzy.common.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 网页gzip压缩
 */
public class GZIPEncodeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        String transferEncoding = getGZIPEncoding((HttpServletRequest) request);
        if (transferEncoding == null) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).setHeader("Content-Encoding",
                    transferEncoding);
            GZIPEncodableResponse wrappedResponse = new GZIPEncodableResponse(
                    (HttpServletResponse) response);
            chain.doFilter(request, wrappedResponse);
            wrappedResponse.flush();
        }
    }

    @Override
    public void destroy() {
    }

    private static String getGZIPEncoding(HttpServletRequest request) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        if (acceptEncoding == null)
            return null;
        acceptEncoding = acceptEncoding.toLowerCase();
        if (acceptEncoding.indexOf("x-gzip") >= 0) {
            return "x-gzip";
        }
        if (acceptEncoding.indexOf("gzip") >= 0) {
            return "gzip";
        }
        return null;
    }
}
